package com.soats.demo8.service.Impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.api.Assert;
import com.baomidou.mybatisplus.extension.api.IErrorCode;
import com.soats.demo8.Util.Result;
import com.soats.demo8.entity.Crimes;
import com.soats.demo8.request.CrimeDataRequest;
import com.soats.demo8.response.CrimeYearData;
import com.soats.demo8.response.CrimeYearEachData;
import com.soats.demo8.service.apiService;
import com.soats.demo8.service.crimesService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class apiServiceImpl implements apiService {

    @Autowired
    private crimesService crimesService;

    @Override
    public JSONArray getRiskIndexCount() {
        // 获取数据
        List<CrimeYearData> crimeDataByYear = crimesService.getCrimeDataByYear();
        // 按年份进行分组
        Map<Integer, List<CrimeYearData>> collect = crimeDataByYear.stream().collect(Collectors.groupingBy(CrimeYearData::getYear));
        // 建立结果对象
        JSONArray result = new JSONArray();
        // 进行数据存储
        for (Integer year : collect.keySet()){
            // 通过Stream流获取并组合成特定格式数据
            List<CrimeYearEachData> eachData = collect.get(year).stream().map(t -> {
                CrimeYearEachData build = CrimeYearEachData.builder().build();
                BeanUtils.copyProperties(t, build);
                return build;
            }).collect(Collectors.toList());
            // 建立存储对象
            JSONObject jo = new JSONObject();
            jo.put("year", year);
            jo.put("riskTop3", eachData);

            result.add(jo);
        }
        return result;
    }

    @Override
    public JSONObject addCrimeData(CrimeDataRequest request) {
        Crimes data = request.getData();
        // 如其它字段值为空（Date类型的值由注解进行校检，int类型不存在null值，故仅有该字段需要校检），则不添加本条记录。
        if (data.getCity().isEmpty()){
            Assert.fail("城市不能为空");
        }
        // 大写城市名称
        data.setCity(data.getCity().toUpperCase());
        // 将新的犯罪记录插入数据库，并返回插入后的事件ID
        int i = crimesService.addCrimeData(request.getData());
        JSONObject jo = new JSONObject();
        jo.put("incidentID", i);
        return jo;
    }
}
